package com.hermit.qmst.UI.main;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.hermit.qmst.R;
import com.hermit.qmst.UI.activity.CallingActivity;
import com.hermit.qmst.UI.activity.SelectCallActivity;
import com.hermit.qmst.adapter.CallLogAdapter;
import com.hermit.qmst.mode.CallLogInfo;
import com.hermit.qmst.mode.ContactInfo;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.Log;
import com.hermit.qmst.tools.Preferences;
import com.hermit.qmst.tools.SipCallHelp;
import com.hermit.qmst.tools.Utils;

import java.util.ArrayList;


public class CallLogFragment extends Fragment implements View.OnClickListener,LoaderManager.LoaderCallbacks<Cursor>{

    private static final String TAG = "CallLogFragment" ;

    private static CallLogFragment mInstance;
    private ArrayList<CallLogInfo> mCallLogList = new ArrayList<CallLogInfo>();

    private ListView mCallLogListView;
    private CallLogAdapter mCallLogAdapter;
    private LoaderManager mLoaderManager;
    private int CALLLOG_LOADER_MANAGER_ID = 1000;
    private View mView;
    private Preferences mPreferences;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mInstance = this;

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (mView == null){
           mView = inflater.inflate(R.layout.activity_tab_calllog,null);
        }else {
            ViewGroup vp =  (ViewGroup)mView.getRootView();
            vp.removeView(mView);

        }

        return mView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

            if (mCallLogListView == null){
                initView();
                mLoaderManager = getLoaderManager();
                mLoaderManager.initLoader(CALLLOG_LOADER_MANAGER_ID,null,this);
            }else {


            }



    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPreferences = new Preferences(getActivity());

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public static CallLogFragment getInstance(){
        return mInstance;
    }

    private void initView(){

        mCallLogListView = (ListView)getActivity().findViewById(R.id.lv_calllog);

        initListener();

    }

    private void initListener(){
        mCallLogListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ContactInfo info = (ContactInfo)parent.getAdapter().getItem(position);
                Common.mCallName = info.getName();
                Common.mCallAera = info.getPhoneAera();
                Common.mCallPhone = info.getPhone1();

                //清空输入框


                String type = mPreferences.getPreferenceStringValue(Preferences.CALL_WAY);
                if (type.equals("0")) {//回拨


                    Intent intent = new Intent(getActivity(),CallingActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);

                }else if (type.equals("1")){//直拨
                    SipCallHelp.placeCallWithOption(null,getActivity(),info.getPhone1());
                }else if (type.equals("2")){//智能拨打

                    if (Common.checkWIFI(getActivity())){
                        SipCallHelp.placeCallWithOption(null,getActivity(),info.getPhone1());
                    }else {
                        Intent intent = new Intent(getActivity(),CallingActivity.class);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);

                    }
                }else {

                    Intent intent = new Intent(getActivity(), SelectCallActivity.class);
                    startActivity(intent);
                    // getActivity().overridePendingTransition(R.anim.fling_in_right2left,R.anim.fling_out_left2right);
                }
            }
        });

    }















    @Override
    public void onClick(View v) {

        switch (v.getId()){



            case R.id.iv_title_right:



                break;
        }

    }


    //实现LoaderManager.LoaderCallbacks办法


    @Override
    public android.support.v4.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {

        /**
         * CursorLoader该类用于加载程序,查询ContentResolver并返回一个指针。这个类实现了装载机协议查询游标的标准方法,
         * 基于AsyncTaskLoader执行游标查询在一个后台线程,以便它不会阻止应用程序的UI。
         */
        Log.i("onCreateLoader","id = " + id,true);
        CursorLoader loader = new CursorLoader(getActivity());
        //设置查询路径
        loader.setUri(CallLog.Calls.CONTENT_URI);
        //设置查询的列
        loader.setProjection(new String[]{CallLog.Calls._ID, CallLog.Calls.DATE, CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME, CallLog.Calls.TYPE });
        //设置查询条件 按时间顺序查询
        loader.setSortOrder(CallLog.Calls.DEFAULT_SORT_ORDER);
        return loader;
    }

    @Override
    public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor data) {
        Log.i("onLoadFinished","id = " + loader.getId(),true);

        boolean c = false;

        while (data.moveToNext()){

            if (!c){
                mCallLogList.clear();
                c = true;
            }

            CallLogInfo info = new CallLogInfo();
            String phone1 = "";//处理之后的
            String phone2 = "";//处理之前的
            phone2 = data.getString(data.getColumnIndex(CallLog.Calls.NUMBER));
            if (phone2 == null || phone2.length() == 0 ){
                continue;
            }
            phone1 = Utils.analysePhoneNumber(phone2);
            if (phone1.length() < 7){
                continue;
            }
            String name = data.getString(data.getColumnIndex(CallLog.Calls.CACHED_NAME));
            info.setName(name);

            info.setPhone1(phone1);
            info.setPhone2(phone2);
            info.setCallLogType(data.getInt(data.getColumnIndex(CallLog.Calls.TYPE)));
            info.setCalltime(data.getString(data.getColumnIndex(CallLog.Calls.DATE)));
//            info.setPhoneAera(data.getString(data.getColumnIndex(CallLog.Calls.CACHED_NUMBER_LABEL)));
            boolean isExist = false;
            //计算通话次数
            for (int i = 0; i < mCallLogList.size(); i++){
                String preName = mCallLogList.get(i).getName();
                String prePhone2 = mCallLogList.get(i).getPhone2();



                if (prePhone2.equals(phone2)){
                    int count = mCallLogList.get(i).getCallCount() + 1;
                    mCallLogList.get(i).setCallCount(count);
                    isExist = true;
                    break;
                }
            }

            if (!isExist){
                mCallLogList.add(info);
            }
        }

        if (c &&mCallLogList.size() > 0 ){
            mCallLogAdapter = new CallLogAdapter(getActivity(),mCallLogList);
            mCallLogListView.setAdapter(mCallLogAdapter);
        }

    }

    @Override
    public void onLoaderReset(android.support.v4.content.Loader<Cursor> loader) {

    }


}
